package cn.dt.ymcc;

import cn.dt.ymcc.result.JSONResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@RestControllerAdvice
public class GlobalExceptionHandle {
    @ExceptionHandler(value = Exception.class)
    public JSONResult exceptionHandler(Exception e) {
        //无权限访问的异常统一处理
        if(e.getClass().getSimpleName().indexOf("AccessDeniedException") != -1){
            return JSONResult.error(
                    "无权限",
                    "403");
        }
        // 把错误信息输入到日志中
        e.printStackTrace();
        return JSONResult.error(
                GlobalError.ERROR_EXCEPTION.getMessage(),
                GlobalError.ERROR_EXCEPTION.getCode());
    }


    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = GlobalException.class)
    public JSONResult exceptionHandler(GlobalException e) {
        e.printStackTrace();
        return JSONResult.error(e.getMessage(),e.getCode());
    }

    /**
     * service-basic本系统的异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JSONResult exceptionHandler(MethodArgumentNotValidException e) {
        e.printStackTrace();
        StringBuilder builder = new StringBuilder();
        for (ObjectError error : e.getBindingResult().getAllErrors()) {
            String message = error.getDefaultMessage();
            builder.append(message).append(";");
        }
        return JSONResult.error(builder.toString());
    }
}
